<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeUnmount, computed, h } from "vue";
import { DynamicTable } from "@/components/DynamicTable";
import { TableColumn } from "@/components/DynamicTable/types";
import DynamicForm from "@/components/DynamicForm/index.vue";
import type { DynamicFormInstance } from "@/components/DynamicForm/types";
import { FormItemConfig } from "@/components/DynamicForm/types";
import { ElMessage, ElTag, ElCard, ElButton } from "element-plus";
import { Refresh } from "@element-plus/icons-vue";
import { useECharts } from "@pureadmin/utils";
import {
  getIntelligenceStatisticsOverview,
  getIntelligenceStatus,
  getIntelligenceWorkflowStatistics,
  getIntelligenceTrend,
} from "../servers";
import { severityLabels } from "../helps";

const props = defineProps<{
  task: string;
}>();

const loading = ref(false);
const overviewData = ref<any>(null); // 统计概览数据
const statusData = ref<any>(null); // 情报状态数据
const workflowStatisticsData = ref<any>(null); // 工作流统计数据
const trendData = ref<any>(null); // 趋势数据（包含严重度分布）
const chartTimeRange = ref(7); // 图表时间范围

// 关键指标（根据实际接口返回数据）
const metrics = computed(() => {
  const overview = overviewData.value;
  const workflow = workflowStatisticsData.value;

  // 从 workflow_statistics 或 workflowStatisticsData 获取数据
  const workflowStats = overview?.workflow_statistics || workflow || {};
  const intelligence = {
    ...workflowStats.intelligence,
    period_days: overviewData.value?.period_days || 0,
  };
  const matching = workflowStats.matching || {};
  const scanning = workflowStats.scanning || {};
  const verification = overview?.verification_statistics || {};
  const security = overview?.security_findings || {};

  return [
    {
      title: "情报总数",
      value: parseInt(intelligence.total) || 0,
      color: "#409EFF",
    },
    {
      title: "今日新增",
      value: parseInt(intelligence.period_days) || 0,
      color: "#67C23A",
    },
    // {
    //   title: "最近新增",
    //   value: parseInt(intelligence.recent) || 0,
    //   color: "#67C23A",
    // },
    {
      title: "匹配资产",
      value: parseInt(matching.total_matches) || 0,
      color: "#E6A23C",
    },
    {
      title: "高危漏洞",
      value: security.high_risk_findings || scanning.high_risk_findings || 0,
      color: "#F56C6C",
    },
    {
      title: "处理成功",
      value: `${(verification.completion_rate * 100).toFixed(1) || 0}%`,
      color: "#909399",
    },
  ];
});

// 趋势图表
const trendsChartRef = ref<HTMLDivElement>();
const trendsChart = useECharts(trendsChartRef);

// 严重度分布饼图
const severityChartRef = ref<HTMLDivElement>();
const severityChart = useECharts(severityChartRef);

// 最近活动数据（从workflow_statistics数据中获取）
const recentActivity = computed(() => {
  const overview = overviewData.value;
  const workflow = workflowStatisticsData.value;
  const workflowStats = overview?.workflow_statistics || workflow || {};
  console.log(overviewData.value, "workflowStatsworkflowStats");

  const matching = workflowStats.matching || {};
  const intelligence = {
    ...overview?.intelligence_statistics,
    period_days: overviewData.value?.period_days || 0,
  };
  const pocRec = workflowStats.poc_recommendation || {};

  return {
    last_24h_matches: parseInt(matching.total_matches) || 0,
    last_24h_new: parseInt(intelligence.recent) || 0,
    last_24h_recommendations: parseInt(pocRec.total_recommendations) || 0,
  };
});

// 来源分布数据（从workflow_statistics数据中获取，显示统计概览）
const sourceData = computed(() => {
  const overview = overviewData.value;
  const workflow = workflowStatisticsData.value;
  const workflowStats = overview?.workflow_statistics || workflow || {};

  const matching = workflowStats.matching || {};
  const pocRec = workflowStats.poc_recommendation || {};
  const scanning = workflowStats.scanning || {};
  const verification = overview?.verification_statistics || {};

  return [
    {
      name: "总匹配数",
      value: parseInt(matching.total_matches) || 0,
    },
    {
      name: "高置信匹配",
      value: parseInt(matching.high_confidence_matches) || 0,
    },
    {
      name: "POC推荐",
      value: parseInt(pocRec.total_recommendations) || 0,
    },
    {
      name: "完成扫描",
      value: scanning.completed_scans || 0,
    },
    {
      name: "完成验证",
      value: verification.completed_verifications || 0,
    },
  ];
});

// 最新告警列表
const alertsList = ref<any[]>([]);

const alertsColumns = ref<TableColumn[]>([
  {
    label: "情报名称",
    prop: "intelligence_name",
    minWidth: 200,
    show: true,
  },
  {
    label: "严重程度",
    prop: "severity",
    width: 120,
    show: true,
    render: (row) => {
      const severityMap: Record<string, any> = {
        严重: { type: "danger" },
        高危: { type: "warning" },
        中危: { type: "info" },
        低危: { type: "success" },
      };
      const severityInfo = severityMap[row.severity] || { type: "info" };
      return h(
        ElTag,
        { type: severityInfo.type, size: "small" },
        () => row.severity
      );
    },
  },
  {
    label: "受影响资产",
    prop: "affected_assets",
    width: 120,
    show: true,
  },
  {
    label: "告警时间",
    prop: "alert_time",
    width: 180,
    show: true,
  },
]);

// 最新活动列表
const activitiesList = ref<any[]>([]);

const activitiesColumns = ref<TableColumn[]>([
  {
    label: "操作",
    prop: "action",
    width: 120,
    show: true,
  },
  {
    label: "详情",
    prop: "details",
    minWidth: 200,
    show: true,
  },
  {
    label: "时间",
    prop: "timestamp",
    width: 180,
    show: true,
  },
]);

// 工作流状态信息（从verification_statistics数据中获取）
// const workflowStatus = computed(() => {
//   const overview = overviewData.value;
//   const verification = overview?.verification_statistics || {};

//   return {
//     status: verification.total_verifications > 0 ? "running" : "stopped",
//     verifying_tasks:
//       verification.total_verifications - verification.completed_verifications ||
//       0,
//     workflow_status:
//       verification.total_verifications > 0 ? "running" : "stopped",
//     completion_rate: verification.completion_rate || 0,
//     total_verifications: verification.total_verifications || 0,
//     completed_verifications: verification.completed_verifications || 0,
//   };
// });

// 刷新频率选择表单
const refreshFormRef = ref<DynamicFormInstance>();
const refreshForm = reactive({
  time_range: "month",
});

const refreshConfig: FormItemConfig[] = [
  {
    key: "time_range",
    name: "时间范围",
    type: "select",
    labelWidth: "80px",
    params: {
      clearable: false,
      options: [
        { label: "今天", value: "today" },
        { label: "本周", value: "week" },
        { label: "本月", value: "month" },
        { label: "本季度", value: "quarter" },
        { label: "本年", value: "year" },
      ],
    },
  },
];

const fetchDashboardData = async () => {
  loading.value = true;
  try {
    // 根据MD文档设计，调用4个GET接口（新增趋势接口）
    const [overviewRes, statusRes, workflowRes, trendRes] = await Promise.all([
      getIntelligenceStatisticsOverview({ days: chartTimeRange.value }),
      getIntelligenceStatus(),
      getIntelligenceWorkflowStatistics(),
      getIntelligenceTrend({ days: chartTimeRange.value }),
    ]);

    // 1. 更新统计概览数据（关键指标）
    if (overviewRes?.data) {
      overviewData.value = overviewRes.data;
    }

    // 2. 更新情报状态数据
    if (statusRes?.data) {
      statusData.value = statusRes.data;
    }

    // 3. 更新工作流统计数据
    if (workflowRes?.data) {
      workflowStatisticsData.value = workflowRes.data;
    }

    // 4. 更新趋势数据（包含严重度分布）
    if (trendRes?.data?.data) {
      trendData.value = trendRes.data.data;
    } else if (trendRes?.data) {
      trendData.value = trendRes.data;
    }

    // 更新告警列表（根据security_findings生成告警）
    const securityFindings = overviewRes?.data?.security_findings || {};
    const alerts = [];
    if (securityFindings.high_risk_findings > 0) {
      alerts.push({
        intelligence_name: "高危安全发现",
        severity: "高危",
        affected_assets: securityFindings.high_risk_findings,
        alert_time: new Date().toLocaleString("zh-CN"),
      });
    }
    if (securityFindings.confirmed_vulnerabilities > 0) {
      alerts.push({
        intelligence_name: "已确认漏洞",
        severity: "中危",
        affected_assets: securityFindings.confirmed_vulnerabilities,
        alert_time: new Date().toLocaleString("zh-CN"),
      });
    }
    alertsList.value = alerts;

    // 更新活动列表（根据workflow_statistics生成活动）
    const workflowStats =
      overviewRes?.data?.workflow_statistics || workflowRes?.data || {};
    const activities = [];
    if (parseInt(workflowStats.intelligence?.recent || 0) > 0) {
      activities.push({
        action: "情报收集",
        details: `新增 ${workflowStats.intelligence.recent} 条情报`,
        timestamp: new Date().toLocaleString("zh-CN"),
      });
    }
    if (parseInt(workflowStats.matching?.total_matches || 0) > 0) {
      activities.push({
        action: "资产匹配",
        details: `完成 ${workflowStats.matching.total_matches} 个匹配`,
        timestamp: new Date().toLocaleString("zh-CN"),
      });
    }
    if (
      parseInt(workflowStats.poc_recommendation?.total_recommendations || 0) > 0
    ) {
      activities.push({
        action: "POC推荐",
        details: `推荐 ${workflowStats.poc_recommendation.total_recommendations} 个POC`,
        timestamp: new Date().toLocaleString("zh-CN"),
      });
    }
    activitiesList.value = activities;

    // 渲染图表
    renderTrendsChart();
    renderSeverityChart();
  } catch (error) {
    ElMessage.error("获取仪表板数据失败");
    console.error("API调用失败:", error);
    // 发生错误时使用默认值
    overviewData.value = null;
    statusData.value = null;
    workflowStatisticsData.value = null;
  } finally {
    loading.value = false;
  }
};

// 渲染趋势图（根据实际数据）
const renderTrendsChart = () => {
  // 优先使用趋势接口返回的数据
  let dates: string[] = [];
  let intelligenceData: number[] = [];
  let matchData: number[] = [];

  if (
    trendData.value?.trend_data &&
    Array.isArray(trendData.value.trend_data)
  ) {
    // 使用接口返回的趋势数据
    const trendDataArray = trendData.value.trend_data;
    dates = trendDataArray.map((item: any) => {
      // 格式化日期，只显示月/日
      const date = new Date(item.date);
      return `${date.getMonth() + 1}/${date.getDate()}`;
    });
    intelligenceData = trendDataArray.map(
      (item: any) => parseInt(item.count) || 0
    );

    // 如果有匹配数据，也使用接口数据
    if (
      trendData.value.match_data &&
      Array.isArray(trendData.value.match_data)
    ) {
      matchData = trendData.value.match_data.map(
        (item: any) => parseInt(item.count) || 0
      );
    }
  } else {
    // 如果没有接口数据，使用备用逻辑
    const overview = overviewData.value;
    const workflow = workflowStatisticsData.value;
    const workflowStats = overview?.workflow_statistics || workflow || {};

    const intelligence = workflowStats.intelligence || {};
    const matching = workflowStats.matching || {};
    const periodDays =
      workflowStats.statistics_period_days ||
      overview?.period_days ||
      chartTimeRange.value;

    // 生成日期标签
    const now = new Date();
    for (let i = periodDays - 1; i >= 0; i--) {
      const date = new Date(now);
      date.setDate(date.getDate() - i);
      dates.push(`${date.getMonth() + 1}/${date.getDate()}`);
    }

    // 使用平均分布来展示趋势
    const totalIntelligence = parseInt(intelligence.total) || 0;
    const recentIntelligence = parseInt(intelligence.recent) || 0;
    const totalMatches = parseInt(matching.total_matches) || 0;

    intelligenceData = new Array(periodDays).fill(0);
    matchData = new Array(periodDays).fill(0);

    if (periodDays > 0) {
      intelligenceData[periodDays - 1] = recentIntelligence;
      const remaining = totalIntelligence - recentIntelligence;
      for (let i = 0; i < periodDays - 1; i++) {
        intelligenceData[i] = Math.floor(remaining / (periodDays - 1));
      }

      const avgMatches = Math.floor(totalMatches / periodDays);
      matchData.fill(avgMatches);
      matchData[periodDays - 1] = totalMatches - avgMatches * (periodDays - 1);
    }
  }

  const option: any = {
    title: {
      text: `情报趋势分析 (${chartTimeRange.value}天)`,
      left: "center",
      textStyle: {
        fontSize: 16,
        fontWeight: "bold",
      },
    },
    tooltip: {
      trigger: "axis" as const,
    },
    legend: {
      data: ["新增情报", "匹配数量"],
      bottom: 0,
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "15%",
      containLabel: true,
    },
    xAxis: {
      type: "category" as const,
      data: dates,
      boundaryGap: false,
    },
    yAxis: {
      type: "value" as const,
    },
    series: [
      {
        name: "新增情报",
        type: "line",
        data: intelligenceData,
        smooth: true,
        itemStyle: { color: "#409EFF" },
      },
      {
        name: "匹配数量",
        type: "line",
        data: matchData,
        smooth: true,
        itemStyle: { color: "#67C23A" },
      },
    ],
  };

  trendsChart.setOptions(option);
};

// 渲染严重度分布饼图
const renderSeverityChart = () => {
  // 使用趋势接口返回的严重度分布数据（饼图数据）
  let severityDistribution = trendData.value?.severity_distribution;

  // 如果接口没有返回，使用默认值
  if (!severityDistribution) {
    severityDistribution = {
      critical: 0,
      high: 0,
      medium: 0,
      low: 0,
      unknown: 0,
    };
  }

  const pieData = [
    {
      name: severityLabels.critical,
      value: severityDistribution.critical || 0,
      itemStyle: { color: "#F56C6C" }, // 红色
    },
    {
      name: severityLabels.high,
      value: severityDistribution.high || 0,
      itemStyle: { color: "#E6A23C" }, // 橙色
    },
    {
      name: severityLabels.medium,
      value: severityDistribution.medium || 0,
      itemStyle: { color: "#409EFF" }, // 蓝色
    },
    {
      name: severityLabels.low,
      value: severityDistribution.low || 0,
      itemStyle: { color: "#67C23A" }, // 绿色
    },
    {
      name: severityLabels.unknown,
      value: severityDistribution.unknown || 0,
      itemStyle: { color: "#909399" }, // 灰色
    },
  ].filter((item) => item.value > 0); // 过滤掉值为0的项

  const option: any = {
    title: {
      text: "漏洞严重度分布",
      left: "center",
      textStyle: {
        fontSize: 16,
        fontWeight: "bold",
      },
    },
    tooltip: {
      trigger: "item",
      formatter: "{a} <br/>{b}: {c} ({d}%)",
    },
    legend: {
      orient: "vertical",
      left: "left",
      bottom: "center",
      data: pieData.map((item) => item.name),
    },
    series: [
      {
        name: "严重度分布",
        type: "pie",
        radius: ["40%", "70%"],
        center: ["60%", "50%"],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: "#fff",
          borderWidth: 2,
        },
        label: {
          show: true,
          formatter: "{b}: {c}\n({d}%)",
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 14,
            fontWeight: "bold",
          },
        },
        data: pieData,
      },
    ],
  };

  severityChart.setOptions(option);
};

const handleRefresh = () => {
  fetchDashboardData();
};

const handleTimeRangeChange = () => {
  fetchDashboardData();
};

onMounted(() => {
  fetchDashboardData();
});

onBeforeUnmount(() => {
  try {
    const trendsInstance = trendsChart.getInstance();
    if (trendsInstance) {
      trendsInstance.dispose();
    }
    const severityInstance = severityChart.getInstance();
    if (severityInstance) {
      severityInstance.dispose();
    }
  } catch (e) {
    // ignore
  }
});
</script>

<template>
  <div>
    <!-- 统计信息筛选 -->
    <el-card shadow="never" style="margin-bottom: 16px">
      <div
        style="
          display: flex;
          justify-content: space-between;
          align-items: center;
        "
      >
        <h3 style="margin: 0">统计信息</h3>
        <div style="display: flex; gap: 12px; align-items: center">
          <el-button :icon="Refresh" @click="handleRefresh">刷新</el-button>
        </div>
      </div>
    </el-card>
    <!-- 关键指标卡片 -->
    <div
      style="
        display: grid;
        grid-template-columns: repeat(5, 1fr);
        gap: 16px;
        margin-bottom: 16px;
      "
    >
      <el-card
        v-for="(metric, index) in metrics"
        :key="index"
        shadow="hover"
        :body-style="{ padding: '20px' }"
      >
        <div
          style="
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            text-align: center;
            height: 100%;
          "
        >
          <div
            style="
              font-size: 18px;
              color: #666;
              margin-bottom: 12px;
              font-weight: 500;
            "
          >
            {{ metric.title }}
          </div>
          <div
            :style="{
              fontSize: '36px',
              fontWeight: 'bold',
              color: metric.color,
              lineHeight: 1,
            }"
          >
            {{ metric.value }}
          </div>
        </div>
      </el-card>
    </div>

    <!-- 告警和待处理任务 -->
    <!-- <el-card shadow="hover" style="margin-bottom: 16px">
      <template #header>
        <span>🚨 告警和待处理任务</span>
      </template>
      <div style="display: flex; flex-direction: column; gap: 12px">
        <div
          v-if="
            (overviewData?.security_findings?.high_risk_findings || 0) > 0 ||
            (overviewData?.workflow_statistics?.scanning?.high_risk_findings ||
              0) > 0
          "
          style="
            padding: 12px;
            background: #fff2e8;
            border-left: 4px solid #f56c6c;
            border-radius: 4px;
          "
        >
          <span style="color: #f56c6c; font-weight: 500"
            >发现{{
              overviewData?.security_findings?.high_risk_findings ||
              overviewData?.workflow_statistics?.scanning?.high_risk_findings ||
              0
            }}个高危漏洞需要立即验证</span
          >
        </div>
        <div
          v-if="workflowStatus.verifying_tasks > 0"
          style="
            padding: 12px;
            background: #e6f7ff;
            border-left: 4px solid #409eff;
            border-radius: 4px;
          "
        >
          <span style="color: #409eff; font-weight: 500"
            >当前有{{ workflowStatus.verifying_tasks }}个验证任务进行中</span
          >
        </div>
        <div
          style="
            padding: 12px;
            background: #f6ffed;
            border-left: 4px solid #52c41a;
            border-radius: 4px;
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
        >
          <span style="color: #52c41a; font-weight: 500">工作流引擎状态：</span>
          <el-tag
            :type="
              workflowStatus.status === 'running'
                ? 'success'
                : workflowStatus.status === 'stopped'
                ? 'danger'
                : 'info'
            "
            size="small"
          >
            {{
              workflowStatus.status === "running"
                ? "🟢 运行中"
                : workflowStatus.status === "stopped"
                ? "🔴 已停止"
                : "🟡 未知"
            }}
          </el-tag>
        </div>
      </div>
    </el-card> -->

    <!-- 最近活动统计 -->
    <el-card shadow="hover" style="margin-bottom: 16px">
      <template #header>
        <span>最近24小时活动</span>
      </template>
      <div
        style="
          display: grid;
          grid-template-columns: repeat(3, 1fr);
          gap: 20px;
          text-align: center;
        "
      >
        <div>
          <div style="font-size: 24px; font-weight: bold; color: #409eff">
            {{ recentActivity.last_24h_matches }}
          </div>
          <div style="font-size: 14px; color: #666; margin-top: 4px">
            匹配数量
          </div>
        </div>
        <div>
          <div style="font-size: 24px; font-weight: bold; color: #67c23a">
            {{ recentActivity.last_24h_new }}
          </div>
          <div style="font-size: 14px; color: #666; margin-top: 4px">
            新增情报
          </div>
        </div>
        <div>
          <div style="font-size: 24px; font-weight: bold; color: #e6a23c">
            {{ recentActivity.last_24h_recommendations }}
          </div>
          <div style="font-size: 14px; color: #666; margin-top: 4px">
            POC推荐
          </div>
        </div>
      </div>
    </el-card>

    <!-- 图表区域 - 两个图表并排 -->
    <div
      style="
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 16px;
        margin-bottom: 16px;
      "
    >
      <!-- 情报收集趋势图 -->
      <el-card shadow="hover">
        <template #header>
          <div
            style="
              display: flex;
              justify-content: space-between;
              align-items: center;
            "
          >
            <span>📈 情报收集趋势图</span>
            <el-select
              v-model="chartTimeRange"
              size="small"
              style="width: 100px"
              @change="fetchDashboardData"
            >
              <el-option label="7天" :value="7"></el-option>
              <el-option label="30天" :value="30"></el-option>
            </el-select>
          </div>
        </template>
        <div
          ref="trendsChartRef"
          style="width: 100%; height: 400px"
          v-loading="loading"
        ></div>
      </el-card>

      <!-- 漏洞严重度分布图 -->
      <el-card shadow="hover">
        <template #header>
          <span>📊 漏洞严重度分布图</span>
        </template>
        <div
          ref="severityChartRef"
          style="width: 100%; height: 400px"
          v-loading="loading"
        ></div>
      </el-card>
    </div>

    <!-- 来源分布 -->
    <el-card shadow="hover" style="margin-bottom: 16px">
      <template #header>
        <span>情报来源分布</span>
      </template>
      <div
        style="
          display: grid;
          grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
          gap: 16px;
        "
      >
        <div
          v-for="(item, index) in sourceData"
          :key="index"
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 16px;
            background: #f8f9fa;
            border-radius: 8px;
            border-left: 4px solid #409eff;
          "
        >
          <span style="font-size: 14px; color: #666">{{ item.name }}</span>
          <span style="font-size: 18px; font-weight: bold; color: #409eff">
            {{ item.value }}
          </span>
        </div>
      </div>
    </el-card>

    <!-- 最新告警和活动 -->
    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px">
      <!-- 最新告警 -->
      <el-card shadow="hover">
        <template #header>
          <span>最新告警</span>
        </template>
        <DynamicTable
          :columns="alertsColumns"
          :data="alertsList"
          :loading="loading"
          :show-header="true"
        />
      </el-card>

      <!-- 最新活动 -->
      <el-card shadow="hover">
        <template #header>
          <span>最新活动</span>
        </template>
        <DynamicTable
          :columns="activitiesColumns"
          :data="activitiesList"
          :loading="loading"
          :show-header="true"
        />
      </el-card>
    </div>
  </div>
</template>

<style scoped lang="scss">
:deep(.el-card__body) {
  padding: 16px;
}
</style>
